#include "GameStateManager.hpp"

using namespace Typhoon;

GameStateManager::GameStateManager() {
}

GameStateManager::~GameStateManager() {
	Exit();
}

bool GameStateManager::Update(float dt) {
	if (states.size()>0) {
		if (states.top()->ShouldExit) {
			Pop();
		} else {
			states.top()->Update(dt);
		}
	}
	return states.size()>0;
}

void GameStateManager::Render() {
	states.top()->Render();
}

void GameStateManager::Push(GameState* state) {
	if (states.size()>0) {
		states.top()->Exited();
	}
	states.push(state);
	state->System = System;
	state->Initialize();
	state->Entered();

	state->OnPush += event_handler(this, &GameStateManager::StatePushed);
}

void GameStateManager::Pop() {
	GameState* state = states.top();
	state->Exited();
	state->OnPush -= event_handler(this, &GameStateManager::StatePushed);
	states.pop();
	delete state;
	if (states.size()>0) {
		states.top()->Entered();
	}
}

void GameStateManager::StateExited(GameState* state) {
	Pop();
}

void GameStateManager::StatePushed(GameState* state) {
	Push(state);
}

void GameStateManager::Exit() {
	while (!states.empty()) {
		Pop();
	}
}

void GameStateManager::UpdateInput(void* input) {
	states.top()->UpdateInput(input);
}
